package com.xbb.controller;

import com.xbb.common.RespResult;
import com.xbb.constant.SessionConstant;
import com.xbb.entity.Commodity;
import com.xbb.entity.User;
import com.xbb.entity.CommodityOrders;
import com.xbb.service.CommodityOrdersService;
import com.xbb.service.CommodityService;
import com.xbb.service.UserService;
import com.xbb.util.DateUtils;
import com.xbb.util.FileUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 兑换订单Controller
 */
@RestController
@CrossOrigin
@RequestMapping("/commodityOrders")
public class CommodityOrdersController {

    @Resource
    private CommodityOrdersService commodityOrdersService;
    @Resource
    private CommodityService commodityService;
    @Resource
    private UserService userService;

    // 根据条件查询分页数据及条数
    @RequestMapping("/data")
    public RespResult data(@RequestParam("page") int page,
                           @RequestParam("limit") int limit,
                           @RequestParam(value = "userId", required = false) Integer userId,
                           @RequestParam(value = "status", required = false) Integer status,
                           @RequestParam(value = "number", required = false) String number,
                           @RequestParam(value = "name", required = false) String name,
                           @RequestParam(value = "cellphone", required = false) String cellphone,
                           @RequestParam(value = "creatDate", required = false) Date creatDate,
                           @RequestParam(value = "commodityId", required = false) Integer commodityId,
                           @RequestParam(value = "staffId", required = false) Integer staffId,
                           HttpSession session) {
        User user = (User) session.getAttribute(SessionConstant.KEY_USER);
        List<CommodityOrders> commodityOrdersList = commodityOrdersService.selectListByPaging(
                page,
                limit,
                userId,
                status,
                number,
                name,
                cellphone,
                creatDate,
                commodityId,
                staffId
        );
        int count = commodityOrdersService.selectCountByPaging(
                userId,
                status,
                number,
                name,
                cellphone,
                creatDate,
                commodityId,
                staffId
        );
        RespResult respResult = new RespResult();
        respResult.success(commodityOrdersList, count);
        return respResult;
    }

    // 查询全部数据
    @RequestMapping("/all")
    public RespResult all() {
        List<CommodityOrders> commodityOrdersList = commodityOrdersService.selectAll();
        RespResult respResult = new RespResult();
        respResult.success(commodityOrdersList);
        return respResult;
    }

    // 根据条件查询列表数据
    @RequestMapping("/list")
    public RespResult list(@RequestBody CommodityOrders commodityOrders) {
        List<CommodityOrders> commodityOrdersList = commodityOrdersService.selectList(commodityOrders);
        RespResult respResult = new RespResult();
        respResult.success(commodityOrdersList);
        return respResult;
    }

    // 根据字段、排序方式、limit条 查询列表数据
    @RequestMapping("/list/limit")
    public RespResult selectListByLimit(@RequestParam(value = "field", required = false) String field,
                                        @RequestParam(value = "sort", required = false) String sort,
                                        @RequestParam(value = "limit", required = false) Integer limit) {
        List<CommodityOrders> commodityOrdersList = commodityOrdersService.selectListByLimit(
                 field, sort, limit
        );
        RespResult respResult = new RespResult();
        respResult.success(commodityOrdersList);
        return respResult;
    }

    // 根据字段查询列表数据
    @RequestMapping("/list/field")
    public RespResult selectListByField(@RequestParam(value = "field", required = false) String field,
                                        @RequestParam(value = "value", required = false) Object value) {
        List<CommodityOrders> commodityOrdersList = commodityOrdersService.selectListByField(
                field, value
        );
        RespResult respResult = new RespResult();
        respResult.success(commodityOrdersList);
        return respResult;
    }

    // 根据条件查询单个数据
    @RequestMapping("/info/dynamic")
    public RespResult infoDynamic(@RequestBody CommodityOrders data) {
        CommodityOrders commodityOrders = commodityOrdersService.selectOne(data);
        RespResult respResult = new RespResult();
        respResult.success(commodityOrders);
        return respResult;
    }

    // 根据ID查询单个数据
    @RequestMapping("/info")
    public RespResult info(@RequestParam("id") Integer id) {
        CommodityOrders commodityOrders = commodityOrdersService.selectByPrimaryKey(id);
        RespResult respResult = new RespResult();
        respResult.success(commodityOrders);
        return respResult;
    }

    // 根据ID查询数据详情
    @RequestMapping("/details")
    public RespResult details(@RequestParam("id") Integer id) {
        CommodityOrders commodityOrders = commodityOrdersService.selectOneByDetails(id);
        RespResult respResult = new RespResult();
        respResult.success(commodityOrders);
        return respResult;
    }

    // 全部条数
    @RequestMapping("/count")
    public RespResult count() {
        int count = commodityOrdersService.selectAllCount();
        RespResult respResult = new RespResult();
        respResult.success(count);
        return respResult;
    }

    // 根据条件查询数据条数
    @RequestMapping("/count/dynamic")
    public RespResult countDynamic(@RequestBody CommodityOrders commodityOrders) {
        int count = commodityOrdersService.selectCount(commodityOrders);
        RespResult respResult = new RespResult();
        respResult.success(count);
        return respResult;
    }

    // 根据条件修改全部数据
    @RequestMapping("/update/all")
    public RespResult updateAll(@RequestBody CommodityOrders commodityOrders) {
        commodityOrdersService.updateAll(commodityOrders);
        RespResult respResult = new RespResult();
        return respResult;
    }

    // 添加数据
    @RequestMapping("/add")
    public RespResult add(@RequestBody CommodityOrders commodityOrders) {
        RespResult respResult = new RespResult();
        User user = userService.selectByPrimaryKey(commodityOrders.getUserId());
        Commodity commodity = commodityService.selectByPrimaryKey(commodityOrders.getCommodityId());
        // 判断用户积分是否足够
        if (user.getIntegral() >= commodity.getIntegrate() * commodityOrders.getQuantity()) {
            if (commodity.getInventory() >= commodityOrders.getQuantity()) {
                commodityOrders.setIntegrate(commodity.getIntegrate() * commodityOrders.getQuantity());
                commodityOrders.setCreatTime(new Date());
                commodityOrders.setNumber(FileUtils.createUUID());
                commodityOrders.setCreatDate(new Date());
                commodityOrders.setYear(DateUtils.getYear());
                commodityOrders.setMonth(DateUtils.getMonth());
                commodityOrdersService.insertSelective(commodityOrders);

                // 兑换量、库存变化
                commodity.setSalesVolume(commodity.getSalesVolume() + commodityOrders.getQuantity());
                commodity.setInventory(commodity.getInventory() - commodityOrders.getQuantity());
                commodityService.updateByPrimaryKeySelective(commodity);

                // 积分变化
                user.setIntegral(user.getIntegral() - commodityOrders.getIntegrate());
                userService.updateByPrimaryKeySelective(user);

                respResult.success(commodityOrders);
            } else {
                respResult.error("操作失败：库存不足");
            }
        } else {
            respResult.error("操作失败：积分不足");
        }
        return respResult;
    }

    // 修改数据
    @RequestMapping("/edit")
    public RespResult edit(@RequestBody CommodityOrders commodityOrders) {
        commodityOrdersService.updateByPrimaryKeySelective(commodityOrders);
        RespResult respResult = new RespResult();
        respResult.success(commodityOrders);
        return respResult;
    }

    // 单个删除
    @RequestMapping("/delete")
    public RespResult delete(@RequestParam("id") Integer id) {
        commodityOrdersService.deleteByPrimaryKey(id);
        return new RespResult();
    }

    // 批量删除
    @RequestMapping("/delete/list")
    public RespResult deleteList(@RequestBody Integer[] idList) {
        for (Integer id : idList) {
            commodityOrdersService.deleteByPrimaryKey(id);
        }
        return new RespResult();
    }

    // 年度兑换量统计
    @RequestMapping("/statistics/year")
    public RespResult statisticsYear () {
        // 柱图数据
        List<String> nameList = new ArrayList<>();
        List<Object> valueList = new ArrayList<>();

        for (int i = 1; i <= 12; i++) {
            int count = commodityOrdersService.selectStatisticByYear(DateUtils.getYear(), i);
            nameList.add(i + "月");
            valueList.add(count);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("nameList", nameList);
        data.put("valueList", valueList);

        RespResult respResult = new RespResult();
        respResult.success(data);
        return respResult;
    }

}
